package cn.tx.security.config;

import cn.tx.security.service.impl.LoginService1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

/**
 * @Package: cn.tx.security.config
 * @Description: 类作用描述
 * @Author Mxb
 * @CreateDate 2020/10/31 16:50
 * @Version 1.0
 */
@Configuration
public class SecurityConfig2 extends WebSecurityConfigurerAdapter {
    //@Autowired
    //private DataSource dataSource;

    @Autowired
    private LoginService1 loginService;

    @Autowired
    private PersistentTokenRepository tokenRepository;

    //@Bean
    //public PersistentTokenRepository persistentTokenRepository() {
    //    JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
    //    tokenRepository.setDataSource(dataSource);
    //    //系统在启动的时候生成“记住我”的数据表（只能使用一次）
    //    tokenRepository.setCreateTableOnStartup(false);
    //    return tokenRepository;
    //}

    /**
     * 定义用户名密码
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(loginService).passwordEncoder(passwordEncoder());
    }

    /**
     * 注入PasswordEncoder 类到spring 容器中
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //自定义登录页
        http.formLogin()
                .loginPage("/login.html") //登录页面设置
                .loginProcessingUrl("/user/login") //设置表单提交访问路径
                .defaultSuccessUrl("/success.html").permitAll(); //登录成功后要跳转的路径

        http.authorizeRequests()
                // 设置哪些路径可以直接访问，不需要认证
                .antMatchers("/", "/test/hello", "user/login")
                .permitAll()
                //.antMatchers("test/index").hasAuthority("menu:system")
                //.antMatchers("test/manager").hasAnyRole("管理员")
                //任何请求，需要认证
                .anyRequest().authenticated();

        http.csrf().disable(); //关闭csrf防护

        http.exceptionHandling().accessDeniedPage("/unauth.html");

        // 开启记住我功能
        http.rememberMe()
                .tokenRepository(tokenRepository)
                .userDetailsService(loginService)
                .tokenValiditySeconds(100); //单位是秒

        //登录注销设置
        http.logout().logoutUrl("/logout")
                .logoutSuccessUrl("/login.html").permitAll();
    }
}
